<?php
namespace App\Service;

use App\Model\BmrUserModel;
use App\Model\FoodModel;
use App\Model\UserFoodModel;
use App\Service\BMR\BMR_Food;
use App\Service\BMR\BMR_Food1;
use App\Service\BMR\Nutrition\Carbohydrate;
use App\Service\BMR\Nutrition\Fat;
use App\Service\BMR\Nutrition\Protein;

class FoodService {


    /**获取脂肪热量
     * @param $weight 多少克
     * @return mixed
     */
    public function getFatHot($weight)
    {
        return $weight * Fat::HOT_PER;
    }

    /**获取蛋白质热量
     * @param $weight 多少克
     * @return mixed
     */
    public function getProteinHot($weight)
    {
        return $weight * Protein::HOT_PER;
    }

    /**获取碳水化合物热量
     * @param $weight 多少克
     * @return mixed
     */
    public function getCarbohydrateHot($weight)
    {
        return $weight * Carbohydrate::HOT_PER;
    }

    /**获取食物的总热量
     * @param object $food
     * ->fat 脂肪重量/克
     * ->protein 蛋白质重量/克
     * ->carbohydrate 碳水化合物重量/克
     * @return array
     * [
     *      fat => 脂肪热量,
     *      protein => 蛋白质热量
     *      carbohydrate => 碳水化合物热量
     * ]
     */
    public function getHot($food) {
        $hot = 0;
        $hot += $this->getFatHot($food->fact); //脂肪
        $hot += $this->getCarbohydrateHot($food->carbohydrate); //碳水化合物
        $hot += $this->getProteinHot($food->protein); //蛋白质

        return $hot;
    }

    /**模糊搜索食物
     * @param $category 食物名
     * @param bool $formatHot 是否需要格式化计算为热量
     * @param bool $findExtra 是否强制采集
     * @return collect
     */
    public function findCategory($category, bool $formatHot, $findExtra = false) {
        $foods = collect();
        if (!$findExtra)
        $foods = FoodModel::where('category', 'like', "%{$category}%")->get();
        if ($findExtra || $foods->count() == 0) {
            //数据库没有找到，则进行实时采集
            $result = (new BMR_Food1())->gather($category);
            if ($result) {
                //如果能采集，则重新查询
                return $this->findCategory($category, $formatHot);
            } else {
                //不能采集，则返回一个空集合
                return collect();
            }
        }
        return $foods->keyBy(function($food){
            //防止重复
            return $food->category;
        })->values()->map(function($food){
            $food->protein = $this->getProteinHot($food->protein);
            $food->fat = $this->getFatHot($food->fat);
            $food->carbohydrate = $this->getCarbohydrateHot($food->carbohydrate);
            return $food;
        });
    }

    /**计算食物的营养重量 按100克换算
     * @param $find 可以是id主键，可以是一个FoodModel实例
     * @param $weight 食物的总重量
     */
    public function countFoodWeight($find, $weight)
    {
        if (!$find instanceof FoodModel) {
            $find = FoodModel::find($find);
        }
        if (!$find) throw new \Exception('无法找到食物');
        $find->fat = ($find->fat / 100) * $weight;
        $find->protein = ($find->protein / 100) * $weight;
        $find->carbohydrate = ($find->carbohydrate / 100) * $weight;
        return $find;
    }

    /**用户添加健身的食物
     * @param BmrUserModel $bmrUserModel
     * @param $params
     */
    public function updateOrCreateUserFood(BmrUserModel $bmrUserModel, $params)
    {
        $id = $params['id'] ?? 0;
        $weight = $params['weight'] ?? 0;


        //计算食物营养重量
        $food = $this->countFoodWeight($id, $weight);
        //健身评测
        $builder = $bmrUserModel->lastBuilder()->first();
        $now = date('Y-m-d H:i:s');
        $condition = [
            'bmr_user_id'   => $bmrUserModel->id,
            'food_id'       => $food->id,
            'user_builder_id'=> $builder->id,
        ];
        $insert = array_merge($condition,[
            'food_weight'        => $weight,
            'food_category'=> $food->category,
            'food_fat'      => number_format($food->fat, 2, '.', ''),
            'food_protein'  => number_format($food->protein, 2, '.', ''),
            'food_carbohydrate'=> number_format($food->carbohydrate, 2, '.', ''),
            'created_at'    => $now,
            'updated_at'    => $now

        ]);
        $result = UserFoodModel::updateOrCreate($condition, $insert);
        if (!$result) {
            return false;
        }
        return $insert;
    }

    /**删除用户食物
     * @param BmrUserModel $bmrUserModel
     * @param $FoodId
     * @return mixed
     */
    public function destroyUserFood(BmrUserModel $bmrUserModel, $FoodId)
    {
        //健身评测
        $builder = $bmrUserModel->lastBuilder()->first();
        return UserFoodModel::where([
            'bmr_user_id'   => $bmrUserModel->id,
            'food_id'       => $FoodId,
            'user_builder_id'=> $builder->id,
        ])->delete();
    }
}